package net.lab1024.sa.base.config;

import lombok.extern.slf4j.Slf4j;
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Jasypt 加密配置
 */
@Configuration
@Slf4j
public class JasyptConfig {
    
    /**
     * 配置Jasypt加密器
     */
    @Bean("jasyptStringEncryptor")
    public StringEncryptor stringEncryptor() {
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        
        // 优先从Java系统属性获取密钥
        String password = System.getProperty("jasypt.encryptor.password");
        log.info("从系统属性获取密钥: {}", password);
        
        // 如果Java系统属性中没有，则尝试从环境变量获取
        if (password == null || password.isEmpty()) {
            password = System.getenv("JASYPT_ENCRYPTOR_PASSWORD");
            log.info("从环境变量获取密钥: {}", password);
        }
        
        // 如果都没有，使用默认值
        if (password == null || password.isEmpty()) {
            password = "soc-web-2024"; // 默认密钥，生产环境建议使用环境变量
        }
        
        config.setPassword(password);
        config.setAlgorithm("PBEWithMD5AndDES");
        config.setKeyObtentionIterations("1000");
        config.setPoolSize("1");
        config.setProviderName("SunJCE");
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setStringOutputType("base64");
        
        encryptor.setConfig(config);
        return encryptor;
    }
}
